package com.cw.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.common.method.CommonMethod;
import com.cw.constant.Constants;
import com.cw.entity.*;
import com.cw.mapper2.HisCwglBedMapper;
import com.cw.mapper2.ThisIiInmaininfoMapper;
import com.cw.mapper2.ThisIiPrepayinMapper;
import com.cw.request.AllSickBedsRequest;
import com.cw.request.EmptyBedsRequest;
import com.cw.response.EmptyBedsDetailResponse;
import com.cw.response.EmptyBedsResponse;
import com.cw.service.IHisCwglBedService;
import com.cw.service.IOccupationBedService;
import com.cw.service.IPatientBedMiddleRjssService;
import com.cw.service.IPatientBedMiddleService;
import com.cw.util.StringUtil;
import com.cw.vo.KongBedListVO;
import com.cw.vo.LeaveAdviceVO;
import com.cw.vo.spdVO;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author smq
 * @since 2021-05-05
 */
@Service
public class HisCwglBedServiceImpl extends ServiceImpl<HisCwglBedMapper, HisCwglBed> implements IHisCwglBedService {

    @Autowired
    private IPatientBedMiddleService patientBedMiddleService;

    @Autowired
    private IPatientBedMiddleRjssService patientBedMiddleRjssService;

    @Autowired
    private IOccupationBedService occupationBedService;

    @Resource
    private ThisIiInmaininfoMapper thisIiInmaininfoMapper;

    @Resource
    private HisCwglBedMapper hisCwglBedMapper;

    @Resource
    private ThisIiPrepayinMapper thisIiPrepayinMapper;

    public static int seniorRoomNum = 3;

    /**
     * 获取空闲床位
     * cww
     *
     * @param
     * @return
     */
    @Override
    public List<EmptyBedsResponse> getEemptyBedsListNew(AllSickBedsRequest param) {
        List<EmptyBedsResponse> resultBeds = new ArrayList<>();

        //根据院区获取所有的记录(院区,病区,科室),呆会用来统计
        List<HisCwglBed> allBeds = baseMapper.getAllBeds(param);

        if (allBeds == null || allBeds.isEmpty()) {
            return resultBeds;
        }
        List<spdVO> allInBedList = thisIiInmaininfoMapper.getInBedInfo(new ArrayList<>());
        allBeds = SetSexRoom(allBeds,allInBedList);
        Integer emptyAllTotal = 0;
        Integer emptyJGAllTotal = 0;
        //所有空床记录
        List<HisCwglBed> emptyBedList = allBeds.stream()
                .filter(t -> t.getBedState().equals("b"))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(emptyBedList)) {
            emptyAllTotal = emptyBedList.size();
            List<HisCwglBed> emptyJGBedList = emptyBedList.stream()
                    .filter(t -> t.getIfGy().equals("1"))
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(emptyJGBedList)) {
                emptyJGAllTotal = emptyJGBedList.size();
            }
        }
        String strEmptyTotal = String.join("/", emptyJGAllTotal.toString(), emptyAllTotal.toString());

        //根据条件筛选 床位类型,床位状态
        List<HisCwglBed> filterList = new ArrayList<>();
        if (!param.getBedType().equals("")) {
            filterList = allBeds.stream()
                    .filter(t -> t.getIfGy().equals(param.getBedType()))
                    .collect(Collectors.toList());
        } else {
            filterList = allBeds;
        }
        if (!param.getBedState().equals("")) {
            filterList = filterList.stream()
                    .filter(t -> t.getBedState().equals(param.getBedState()))
                    .collect(Collectors.toList());
        }

        //获得在床人员床位号
        List<String> inBedNoList = allInBedList.stream().map(t -> t.getBedNo()).collect(Collectors.toList());

        //获取已预约集管床位
        List<PatientBedMiddle> patientList = patientBedMiddleService.getAllRegisterBeds();

        //获取真正预约床位信息
        patientList = getRealSubscribe(patientList, inBedNoList);

        //根据病区分组(页面上显示病区分组)
        Map<String, List<HisCwglBed>> groupList = filterList.stream()
                .collect(Collectors.groupingBy(t -> t.getNurseCellCode() + "-" + t.getDeptCode()));

        Iterator<String> it = groupList.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            //这里可能存在一个病区多个科室的情况,所以这里要根据科室分一下组
            List<HisCwglBed> operLst = allBeds.stream()
                    .filter(t -> (t.getNurseCellCode() + "-" + t.getDeptCode()).equals(key))
                    .collect(Collectors.toList());
            HisCwglBed info = operLst.get(0);

            //非空床
            List<HisCwglBed> filterNoEmptyBedList = operLst.stream()
                    .filter(t -> t.getBedState().equals("a"))
                    .collect(Collectors.toList());
            //空床
            List<HisCwglBed> filterEmptyBedList = operLst.stream()
                    .filter(t -> t.getBedState().equals("b"))
                    .collect(Collectors.toList());
            //集管床位
            List<HisCwglBed> JGList = operLst.stream()
                    .filter(t -> t.getIfGy().equals("1"))
                    .collect(Collectors.toList());

            List<HisCwglBed> JGEmptyList = JGList.stream()
                    .filter(t -> t.getBedState().equals("b"))
                    .collect(Collectors.toList());
            //男性集管床位空床
            List<HisCwglBed> JGManEmptyList = JGEmptyList.stream()
                    .filter(t -> t.getBedSex().equals("1"))
                    .collect(Collectors.toList());
            //女性集管床位空床
            List<HisCwglBed> JGWomanEmptyList = JGEmptyList.stream()
                    .filter(t -> t.getBedSex().equals("2"))
                    .collect(Collectors.toList());
            //不分男女集管床位空床
            List<HisCwglBed> JGUnKownEmptyList = JGEmptyList.stream()
                    .filter(t -> t.getBedSex().equals("3"))
                    .collect(Collectors.toList());
            //非集管床位
            List<HisCwglBed> FJGList = operLst.stream()
                    .filter(t -> t.getIfGy().equals("0"))
                    .collect(Collectors.toList());
            //非集管床位空床
            List<HisCwglBed> FJGEmptyList = FJGList.stream()
                    .filter(t -> t.getBedState().equals("b"))
                    .collect(Collectors.toList());
            //男性非集管床位空床
            List<HisCwglBed> FJGManEmptyList = FJGEmptyList.stream()
                    .filter(t -> t.getBedSex().equals("1"))
                    .collect(Collectors.toList());
            //女性非集管床位空床
            List<HisCwglBed> FJGWomanEmptyList = FJGEmptyList.stream()
                    .filter(t -> t.getBedSex().equals("2"))
                    .collect(Collectors.toList());
            //不分男女非集管床位空床
            List<HisCwglBed> FJGUnKownEmptyList = FJGEmptyList.stream()
                    .filter(t -> t.getBedSex().equals("3"))
                    .collect(Collectors.toList());
            //科室匹配预约床位
            List<PatientBedMiddle> matchPatientList = patientList.stream()
                    .filter(t -> (t.getNurseCellCode() + "-" + t.getDeptCode()).equals(key))
                    .collect(Collectors.toList());
            EmptyBedsResponse bedInfo = new EmptyBedsResponse();
            bedInfo.setAreaCode(info.getNurseCellCode());  //院区编码
            bedInfo.setAreaName(info.getNurseCellName());   //病区名称
            bedInfo.setDeptCode(info.getDeptCode());        //科室编码
            bedInfo.setDeptName(info.getDeptName());       // 科室名称
            bedInfo.setYeadCode(info.getYard());          //院区编码
            if (info.getYard().equals("1"))               //三香浒关的编码  1是三香 2是浒关
            {
                bedInfo.setYeadName("三香总院");
            } else if (info.getYard().equals("2")) {
                bedInfo.setYeadName("浒关院区");
            }
            bedInfo.setBedsCount(operLst.size());   // 床位总数
            bedInfo.setUsedBedsCount(filterNoEmptyBedList.size()); //已使用床位数量
            bedInfo.setEmptyBedsCount(filterEmptyBedList.size());  //空闲床位数量
            BigDecimal total = new BigDecimal(operLst.size());
            BigDecimal noEmptyTotal = new BigDecimal(filterNoEmptyBedList.size()); //不空的男性集管床位
            BigDecimal emptyTotal = new BigDecimal(filterEmptyBedList.size()); //空的男性集管床位
            bedInfo.setUsedBedsCountDouble(noEmptyTotal.multiply(new BigDecimal(100))
                    .divide(total, 2, BigDecimal.ROUND_HALF_UP)
                    .doubleValue()); //已使用床位占比
            bedInfo.setEmptyBedsCountDouble(emptyTotal.multiply(new BigDecimal(100))
                    .divide(total, 2, BigDecimal.ROUND_HALF_UP)
                    .doubleValue());  //空闲床位占比
            bedInfo.setFocusManager(JGList.size()); //集管床位
            bedInfo.setNoFocusManager(FJGList.size()); //非集管床位
            bedInfo.setManEmptyBedsCount(JGManEmptyList.size()); //男空床数量
            bedInfo.setWomanEmptyBedsCount(JGWomanEmptyList.size()); //女空床数量
            bedInfo.setUnknownEmptyBedsCount(JGUnKownEmptyList.size()); //不明性别空床数量

            bedInfo.setManEmptyBedsCount1(FJGManEmptyList.size()); //非集管男空床数量
            bedInfo.setWomanEmptyBedsCount1(FJGWomanEmptyList.size()); //非集管女空床数量
            bedInfo.setUnknownEmptyBedsCount1(FJGUnKownEmptyList.size()); //非集管不明性别空床数量
            bedInfo.setRegisterBedCount(matchPatientList.size()); //已登记床位数量
            bedInfo.setStrEmptyTotal(strEmptyTotal);
            resultBeds.add(bedInfo);
        }

        //科室名称特殊处理
        resultBeds.forEach(item -> {
            switch (item.getAreaCode()) {

                case "2509":
                    item.setDeptName("肝胆外科");
                    break;
                case "2510":
                    item.setDeptName("胃肠外科");
                    break;
                case "2511":
                    item.setDeptName("关节外科");
                    break;
                case "2609":
                    item.setDeptName("甲乳外科");
                    break;
                case "2611":
                    item.setDeptName("脊柱外科");
                    break;
                case "2731":
                    item.setDeptName("ICU-A");
                    break;
                case "2732":
                    item.setDeptName("ICU-B");
                    break;
                case "2733":
                    item.setDeptName("ICU-C");
                    break;
                case "2734":
                    item.setDeptName("ICU-D");
                    break;
                default:
                    break;
            }
        });
        resultBeds = resultBeds.stream()
                .sorted(Comparator.comparing(EmptyBedsResponse::getAreaCode))
                .collect(Collectors.toList());
        return resultBeds;
    }


    /**
     * 给病床赋属性
     *
     * @param allBeds 所有病床信息
     * @return 1.将非空床的人员先进行性别赋值(根据别人住院信息)
     * 2.根据病区-科室-房间号进行分组
     * 3.判断每组的床位数，小于等于3的为高级病房，否则为普通病房
     * 4.高级病房判断有没有住人，如果有人住院，其他床位的属性赋成该病人属性
     * cww
     */
    private List<HisCwglBed> SetSexRoom(List<HisCwglBed> allBeds,List<spdVO> allInBedList) {
        List<HisCwglBed> newAllBeds = new ArrayList<>();
        //呼吸科不分高级病房，空床全部默认为不分性别
        List<String> specialDept = new ArrayList<>();
        specialDept.add("2615-1023");  //西十五病区   呼吸科

        //获得床位号
        List<String> inBedNoList = allInBedList.stream().map(t -> t.getBedNo()).collect(Collectors.toList());
        //获得病床号编码
        List<String> allBedNos = allBeds.stream().map(t -> t.getBedNo()).collect(Collectors.toList());
        List<spdVO> inBedList = allInBedList.stream()
                .filter(t -> allBedNos.contains(t.getBedNo()))
                .collect(Collectors.toList());
        CommonMethod methodClass = new CommonMethod();
        //初始化
        allBeds.forEach(item -> {
            item.setSex("3");
            item.setBedSex("3");
            item.setSexColor(Constants.threeDiv);
            item.setName(methodClass.getBedName(item.getBedNo()));
        });

        List<HisCwglBed> highGradeBedLst = new ArrayList<>(); //高级病房床位
        List<HisCwglBed> generalBedLst = new ArrayList<>();//普通病房床位
        Map<String, List<HisCwglBed>> groupBeds = allBeds.stream()
                .collect(Collectors.groupingBy(t -> t.getNurseCellCode() + "-" + t.getDeptCode() + "-" + t.getRoomNo()));
        Iterator<String> it = groupBeds.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            List<HisCwglBed> keyList = groupBeds.get(key);
            if (keyList.size() <= seniorRoomNum) {
                highGradeBedLst.addAll(keyList);
            } else {
                generalBedLst.addAll(keyList);
            }
        }

        /**
         * 高级病房床位性别处理
         * */
        //高级病房非空床
        List<HisCwglBed> highGradeNoEmptyBedList = highGradeBedLst.stream()
                .filter(t -> inBedNoList.contains(t.getBedNo()))
                .collect(Collectors.toList());
        //高级病房空床
        List<HisCwglBed> highGradeEmptyBedList = highGradeBedLst.stream()
                .filter(t -> !inBedNoList.contains(t.getBedNo()))
                .collect(Collectors.toList());
        //高级病房非空床赋值
        highGradeNoEmptyBedList.forEach(item -> {
            spdVO matchInfo = inBedList.stream()
                    .filter(t -> t.getBedNo().equals(item.getBedNo()))
                    .findFirst()
                    .orElse(null);
            SetSexValue(matchInfo, item);
            assert matchInfo != null;
            item.setPatinetName(matchInfo.getName());//患者姓名
            item.setBedState("a");//将床位状态赋为a,因为数据库的床位状态数据不一定准确
            item.setSpFlag(matchInfo.getSpFlag());//特殊病人标识
        });

        //高级病房空床赋值
        //1.获取一条同房间号住院人员信息,如果匹配到则 赋值该对应的性别,没有匹配到赋不分性别值
        highGradeEmptyBedList.forEach(item -> {
            List<HisCwglBed> matchLstInfo = highGradeNoEmptyBedList.stream()
                    .filter(t -> (t.getNurseCellCode() + "-" + t.getDeptCode() + "-" + t.getRoomNo()).equals(item.getNurseCellCode() + "-" + item.getDeptCode() + "-" + item.getRoomNo()))
                    .collect(Collectors.toList());
            String concatStr = String.join("-", item.getNurseCellCode(), item.getDeptCode());
            item.setBedState("b");//将床位状态赋为b,因为数据库的床位状态数据不一定准确

            List<String> sexCollect = matchLstInfo.stream()
                    .map(HisCwglBed::getSex)
                    .distinct()
                    .collect(Collectors.toList());
            if (sexCollect.size() == 1 && !specialDept.contains(concatStr)) {
                item.setSex(matchLstInfo.get(0).getSex());
                item.setBedSex(matchLstInfo.get(0).getSex());
                if (matchLstInfo.get(0).getSex().equals("1")) {
                    item.setSexColor(Constants.twoDiv);
                } else if (matchLstInfo.get(0).getSex().equals("2")) {
                    item.setSexColor(Constants.fiveDiv);
                }
            }
        });

        //普通病房床位性别处理
        //普通病房非空床
        List<HisCwglBed> generalNoEmptyBedList = generalBedLst.stream()
                .filter(t -> inBedNoList.contains(t.getBedNo()))
                .collect(Collectors.toList());
        //普通病房空床
        List<HisCwglBed> generalEmptyBedList = generalBedLst.stream()
                .filter(t -> !inBedNoList.contains(t.getBedNo()))
                .collect(Collectors.toList());

        //普通病房非空床赋值
        generalNoEmptyBedList.forEach(item -> {
            spdVO matchInfo = inBedList.stream()
                    .filter(t -> t.getBedNo().equals(item.getBedNo()))
                    .findFirst()
                    .orElse(null);
            SetSexValue(matchInfo, item);
            item.setPatinetName(matchInfo.getName());//患者姓名
            item.setBedState("a");//将床位状态赋为a,因为数据库的床位状态数据不一定准确
            item.setSpFlag(matchInfo.getSpFlag());//特殊病人标识 1:是 0:否 新加字段
        });

        //将床位状态赋为b,因为数据库的床位状态数据不一定准确
        generalEmptyBedList.forEach(item -> {
            item.setBedState("b");
        });
        return allBeds;
    }

    /**
     * 给床位赋性别属性
     */
    private void SetSexValue(spdVO matchInfo, HisCwglBed item) {
        if ((matchInfo != null && matchInfo.getSex() != null)) {
            item.setSex(matchInfo.getSex());
            item.setBedSex(matchInfo.getSex());
            if (matchInfo.getSex().equals("1")) {
                item.setSexColor(Constants.oneDiv);
            } else if (matchInfo.getSex().equals("2")) {
                item.setSexColor(Constants.fourDiv);
            }
        }
    }

    /**
     * 获取空闲床位详情
     *
     * @return
     */
    @Override
    public Object getEemptyBedsDetailsNew(AllSickBedsRequest param) {
        List<HisCwglBed> beds = baseMapper.getAllBeds(param);

        if (CollectionUtils.isEmpty(beds)) {
            return new ArrayList<>();
        }

        List<spdVO> allInBedList = thisIiInmaininfoMapper.getInBedInfo(new ArrayList<>());
        SetSexRoom(beds,allInBedList);
        // 根据条件筛选床位类型、床位状态
        List<HisCwglBed> filterList = new ArrayList<>();
        if (!param.getBedType().isEmpty()) {
            filterList = beds.stream()
                    .filter(t -> t.getIfGy().equals(param.getBedType()))
                    .collect(Collectors.toList());
        } else {
            filterList = beds;
        }
        if (!param.getBedState().isEmpty()) {
            filterList = filterList.stream()
                    .filter(t -> t.getBedState().equals(param.getBedState()))
                    .collect(Collectors.toList());
        }
        AppointmentLabel(filterList);
        //5-31 根据map的key进行排序
        Map<String, List<HisCwglBed>> groupList = filterList.stream()
                .collect(Collectors.groupingBy(t -> t.getDeptName() + t.getNurseCellName() + "-" + t.getRoomNo()));
        Set<String> strings = groupList.keySet();
        ArrayList<String> list = new ArrayList<>(strings);
        list.sort(Comparator.naturalOrder());
        LinkedHashMap<String, List<HisCwglBed>> map = new LinkedHashMap<>();
        list.forEach(item -> map.put(item, groupList.get(item)));
        return map;
    }

    /**
     * 预约床位/占床赋值
     */
    public void AppointmentLabel(List<HisCwglBed> list) {
        //获取已预约集管床位
        List<PatientBedMiddle> patientList = patientBedMiddleService.getAllRegisterBeds();
        patientList.forEach(item -> {
            HisCwglBed matchBedInfo = list.stream()
                    .filter(t -> t.getBedNo().equals(item.getBedNo()))
                    .findFirst()
                    .orElse(null);
            if (matchBedInfo != null) {
                matchBedInfo.setInpatientNo(item.getPreid().toString());
                matchBedInfo.setPatinetName(item.getName());
                matchBedInfo.setIsHisConfirm("1");
                matchBedInfo.setIsNotChange("0");
            }
        });
        //获取占床人员信息
        List<OccupationBed> occupationBedList = occupationBedService.getOccupiedBed(Constants.OCCUPATION_BED_USED);
        occupationBedList.forEach(item -> {
            HisCwglBed matchOccBed = list.stream()
                    .filter(t -> t.getBedNo().equals(item.getBedNo()))
                    .findFirst()
                    .orElse(null);
            if (matchOccBed != null) {
                matchOccBed.setPatinetName(item.getPatientName());
                matchOccBed.setOccupationState("0");
                matchOccBed.setOccupationId(item.getId());
            }
        });
    }

    /**
     * 床位预约详细列表（所有床位明细信息）
     */
    @Override
    public Object getReservationDetail(AllSickBedsRequest param) {
        List<HisCwglBed> ylzzNameList = new ArrayList<>();
        List<LeaveAdviceVO> leaveAdviceVOList = new ArrayList<>();
        List<HisCwglBed> beds = baseMapper.getAllBeds(param);
        if (CollectionUtils.isEmpty(beds)) {
            return new ArrayList<>();
        }

        //这里查明细需要构造一个查询条件类,保证有条件查询,提升查询速度
        spdVO spdVOInfo = new spdVO();
        spdVOInfo.setYard(StringUtil.isEmpty(param.getDistrictCode())?"":param.getDistrictCode());
        spdVOInfo.setNurseCellCode(StringUtil.isEmpty(param.getAreaCode())?"":param.getAreaCode());
        List<spdVO> allInBedList = thisIiInmaininfoMapper.getSPDInBedInfo(spdVOInfo);
        SetSexRoom(beds,allInBedList);
        //获得在床人员床位号
        List<String> inBedNoList = allInBedList.stream().map(spdVO::getBedNo).collect(Collectors.toList());
        //获取已预约集管床位
        List<PatientBedMiddle> patientList = patientBedMiddleService.getAllRegisterBeds();
        //获取真正预约床位信息
        patientList = getRealSubscribe(patientList, inBedNoList);
        //获取占床人员信息
        List<OccupationBed> occupationBedList = occupationBedService.getOccupiedBed(Constants.OCCUPATION_BED_USED);

        for (HisCwglBed bed : beds) {
            PatientBedMiddle match = patientList.stream()
                    .filter(t -> t.getBedNo().equals(bed.getBedNo()))
                    .findFirst()
                    .orElse(null);
            OccupationBed matchOccBed = occupationBedList.stream()
                    .filter(t -> t.getBedNo().equals(bed.getBedNo()))
                    .findFirst()
                    .orElse(null);
            if (match != null) {
                bed.setInpatientNo(match.getPreid().toString());
                bed.setPatinetName(match.getName());
                bed.setIsHisConfirm("1");
                bed.setIsNotChange("0");
            }
            if (matchOccBed != null) {
                bed.setPatinetName(matchOccBed.getPatientName());
                bed.setOccupationState("0");
                bed.setOccupationId(matchOccBed.getId());
            }
        }

        //根据条件筛选 床位类型,床位状态
        List<HisCwglBed> filterList = new ArrayList<>();
        if (!param.getBedType().equals("")) {
            filterList = beds.stream().filter(t -> t.getIfGy().equals(param.getBedType())).collect(Collectors.toList());
        } else {
            filterList = beds;
        }
        if (!param.getBedState().equals("")) {
            filterList = filterList.stream()
                    .filter(t -> t.getBedState().equals(param.getBedState()))
                    .collect(Collectors.toList());
        }
        //根据住院证ZY***匹配住院视图，取医疗组组长姓名编号
        List<HisCwglBed> zyLike = new ArrayList<>();
        for (HisCwglBed hisCwglBed : filterList) {
            HisCwglBed copy = new HisCwglBed();
            if (hisCwglBed.getInpatientNo() == null) {
                continue;
            }
            BeanUtils.copyProperties(hisCwglBed, copy);
            zyLike.add(copy);
        }
        if (!zyLike.isEmpty()) {
            List<String> inpatientNoList = zyLike.stream().map(HisCwglBed::getInpatientNo).collect(Collectors.toList());
            //这里加判断是因为，床位系统里的查询不会出现住院证超过1000的情况，只有在外链查询的时候才会超过1000的情况
            if (inpatientNoList.size() > 1000) {
                int batchSize = 1000;
                List<List<String>> batches = Lists.partition(inpatientNoList, batchSize);
                for (List<String> batchList : batches) {
                    List<HisCwglBed> ylzzNameVO = thisIiInmaininfoMapper.listYlzzNameList(batchList);
                    ylzzNameList.addAll(ylzzNameVO);
                    List<LeaveAdviceVO> leaveAdviceVO = thisIiPrepayinMapper.leaveAdviceInpatientNoList(batchList);
                    leaveAdviceVOList.addAll(leaveAdviceVO);
                }
            } else if (inpatientNoList.size() < 1000) {
                ylzzNameList = thisIiInmaininfoMapper.listYlzzNameList(inpatientNoList);
                leaveAdviceVOList = thisIiPrepayinMapper.leaveAdviceInpatientNoList(inpatientNoList);
            }
            for (HisCwglBed item : ylzzNameList) {
                for (HisCwglBed hisCwglBed : filterList) {
                    if (item.getInpatientNo().equals(hisCwglBed.getInpatientNo())) {
                        hisCwglBed.setYlzzCode(item.getYlzzCode());
                        hisCwglBed.setYlzzName(item.getYlzzName());
                    }
                }
            }
            //选择床位”背景色标注“今日出院”，“明日出院”的患者，用不同色醒目区分
            //出院医嘱的患者信息
            for (LeaveAdviceVO leaveAdviceVO : leaveAdviceVOList) {
                for (HisCwglBed info : filterList) {
                    if (leaveAdviceVO.getInpatientNo().equals(info.getInpatientNo())) {
                        String changeType = leaveAdviceVO.getChangeType();
                        if ("临时出院".equals(changeType) || "自动出院".equals(changeType)) {
                            info.setChangeType("今日出院");
                        } else {
                            info.setChangeType(leaveAdviceVO.getChangeType());
                        }
                    }
                }
            }
        }


        Map<String, List<HisCwglBed>> groupList = filterList.stream()
                .collect(Collectors.groupingBy(HisCwglBed::getRoomNo));
        List<BedsDetailInfo> resultLst = new ArrayList<>();
        Iterator<String> it = groupList.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            BedsDetailInfo info = new BedsDetailInfo();
            info.setRoomNum(key);
            info.setChildren(groupList.get(key));
            resultLst.add(info);
        }
        //如果房间号不全为数字,排序特殊处理
        List<BedsDetailInfo> strList = new ArrayList<>();
        List<BedsDetailInfo> intList = new ArrayList<>();

        Pattern pattern = Pattern.compile("[0-9]*");
        for (BedsDetailInfo item : resultLst) {
            if (pattern.matcher(item.getRoomNum()).matches()) {
                item.setIntRoomNum(Integer.valueOf(item.getRoomNum()));
                intList.add(item);
            } else {
                strList.add(item);
            }
        }
        strList = strList.stream()
                .sorted(Comparator.comparing(BedsDetailInfo::getRoomNum))
                .collect(Collectors.toList());
        intList = intList.stream()
                .sorted(Comparator.comparing(BedsDetailInfo::getIntRoomNum))
                .collect(Collectors.toList());
        resultLst = new ArrayList<>();
        resultLst.addAll(strList);
        resultLst.addAll(intList);
        return resultLst;
    }

    @Override
    public Object getReservationRjssDetail(AllSickBedsRequest param) {
        List<HisCwglBed> beds = baseMapper.getAllBeds(param);
        if (CollectionUtils.isEmpty(beds)) {
            return new ArrayList<>();
        }
        List<spdVO> allInBedList = thisIiInmaininfoMapper.getInBedInfo(new ArrayList<>());
        SetSexRoom(beds,allInBedList);
        //获得在床人员床位号
        List<String> inBedNoList = allInBedList.stream().map(spdVO::getBedNo).collect(Collectors.toList());
        //获取已预约集管床位
        List<PatientBedMiddleRjss> patientList = patientBedMiddleRjssService.getAllRegisterBeds();

        //获取真正预约床位信息
        patientList = getRealSubscribeRjss(patientList, inBedNoList);
        //获取占床人员信息
        List<OccupationBed> occupationBedList = occupationBedService.getOccupiedBed(Constants.OCCUPATION_BED_USED);

        for (HisCwglBed bed : beds) {
            PatientBedMiddleRjss match = patientList.stream()
                    .filter(t -> t.getBedNo().equals(bed.getBedNo()))
                    .findFirst()
                    .orElse(null);
            OccupationBed matchOccBed = occupationBedList.stream()
                    .filter(t -> t.getBedNo().equals(bed.getBedNo()))
                    .findFirst()
                    .orElse(null);
            if (match != null) {
                bed.setInpatientNo(match.getPreid().toString());
                bed.setPatinetName(match.getName());
                bed.setIsHisConfirm("1");
                bed.setIsNotChange("0");
            }
            if (matchOccBed != null) {
                bed.setPatinetName(matchOccBed.getPatientName());
                bed.setOccupationState("0");
                bed.setOccupationId(matchOccBed.getId());
            }
        }

        //根据条件筛选 床位类型,床位状态
        List<HisCwglBed> filterList = new ArrayList<>();
        if (!param.getBedType().equals("")) {
            filterList = beds.stream().filter(t -> t.getIfGy().equals(param.getBedType())).collect(Collectors.toList());
        } else {
            filterList = beds;
        }
        if (!param.getBedState().equals("")) {
            filterList = filterList.stream()
                    .filter(t -> t.getBedState().equals(param.getBedState()))
                    .collect(Collectors.toList());
        }
        Map<String, List<HisCwglBed>> groupList = filterList.stream()
                .collect(Collectors.groupingBy(t -> t.getRoomNo()));
        List<BedsDetailInfo> resultLst = new ArrayList<>();
        Iterator<String> it = groupList.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            BedsDetailInfo info = new BedsDetailInfo();
            info.setRoomNum(key);
            info.setChildren(groupList.get(key));
            resultLst.add(info);
        }
        //如果房间号不全为数字,排序特殊处理
        List<BedsDetailInfo> strList = new ArrayList<>();
        List<BedsDetailInfo> intList = new ArrayList<>();

        Pattern pattern = Pattern.compile("[0-9]*");
        for (BedsDetailInfo item : resultLst) {
            if (pattern.matcher(item.getRoomNum()).matches()) {
                item.setIntRoomNum(Integer.valueOf(item.getRoomNum()));
                intList.add(item);
            } else {
                strList.add(item);
            }
        }
        strList = strList.stream()
                .sorted(Comparator.comparing(BedsDetailInfo::getRoomNum))
                .collect(Collectors.toList());
        intList = intList.stream()
                .sorted(Comparator.comparing(BedsDetailInfo::getIntRoomNum))
                .collect(Collectors.toList());
        resultLst = new ArrayList<>();
        resultLst.addAll(strList);
        resultLst.addAll(intList);

        return resultLst;
    }

    /**
     * 获取空闲床位详情
     * 要改
     *
     * @return
     */
    @Override
    public Object getEemptysByPatien(EmptyBedsRequest emptyBedsRequest) {
        List<EmptyBedsDetailResponse> bedsDetailList = new ArrayList<>();
        return bedsDetailList;
    }

    /**
     * 获取 集中管理空床/集中管理床位的总床位
     * 要改
     *
     * @param yard 院区 1三香 2浒关
     * @return java.lang.String
     * @author ly
     * @date 2021/6/7 9:31
     */
    @Override
    public String getAllManageBed(String yard) {
        //集中管理床位的总床位
        Integer allManageBed = hisCwglBedMapper.getAllManageBed("b", yard, null);
        //获取空的集中管理床位
        Integer getEmptyBedCount = hisCwglBedMapper.getAllManageBed("b", yard, "1");
        return getEmptyBedCount + "/" + allManageBed;
    }

    @Override
    public List<KongBedListVO> getKongBedList(String nurseCellCode) {
        return hisCwglBedMapper.getKongBedList(nurseCellCode);
    }


    /**
     * 获取真正预约床位信息
     * param
     * patientList 预约列表
     * inBedNoList  在床床位号
     */
    public List<PatientBedMiddle> getRealSubscribe(List<PatientBedMiddle> patientList, List<String> inBedNoList) {
        if (patientList != null && !patientList.isEmpty() && inBedNoList != null && !inBedNoList.isEmpty()) {
            patientList = patientList.stream()
                    .filter(t -> !inBedNoList.contains(t.getBedNo()))
                    .collect(Collectors.toList());
        }
        return patientList;
    }

    public List<PatientBedMiddleRjss> getRealSubscribeRjss(List<PatientBedMiddleRjss> patientList,
                                                           List<String> inBedNoList) {
        if (patientList != null && !patientList.isEmpty() && inBedNoList != null && !inBedNoList.isEmpty()) {
            patientList = patientList.stream()
                    .filter(t -> !inBedNoList.contains(t.getBedNo()))
                    .collect(Collectors.toList());
        }
        return patientList;
    }
}
